package com.demo.base.redis.helper;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description Redis客户端 操作Redis数据
 * @date 2023/3/10 2:32 PM
 */
@Component
@Slf4j
public class RedisHelper {

    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 向redis中设值
     *
     * @param key 使在用 a:b:id 的形式，使用 rdm 查看 redis 情况时，看到分层文件夹的展示形式，便于管理
     * @param value
     * @return
     */
    public boolean set(String key, String value) {
        boolean result = false;
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            result = true;
        } catch (Exception ex) {
            log.error("Redis设置缓存失败，原因：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 向redis中设值，同时设置过期时间
     *
     * @param key
     * @param value
     * @param time
     * @return
     */
    public boolean set(String key, String value, Long time) {
        boolean result = false;
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            expire(key, time);
            result = true;
        } catch (Exception ex) {
            log.error("Redis设置过期缓存失败，原因：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 获取redis中的值
     *
     * @param key
     * @return
     */
    public String get(String key) {
        String result = null;
        try {
            result = stringRedisTemplate.opsForValue().get(key);
        } catch (Exception ex) {
            log.error("Redis获取缓存失败，原因：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 设置key的过期时间 单位：s
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, Long time) {
        boolean result = false;
        try {
            if (time > 0) {
                stringRedisTemplate.expire(key, time, TimeUnit.SECONDS);
                result = true;
            }
        } catch (Exception ex) {
            log.error("Redis设置缓存过期时间失败，原因：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 根据key删除对应value
     *
     * @param key
     * @return
     */
    public boolean remove(String key) {
        boolean result = false;
        try {
            stringRedisTemplate.delete(key);
            result = true;
        } catch (Exception ex) {
            log.error("Redis移除缓存失败，原因：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 根据key判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(String key) {
        boolean result = false;
        try {
            result = Boolean.TRUE.equals(stringRedisTemplate.hasKey(key));
        } catch (Exception ex) {
            log.error("Redis查询缓存是否存在失败，原因：{}", ex.getMessage());
        }
        return result;
    }

    /**
     * 根据表达式批量删除Keys 异步方法
     *
     * @param pattern
     * @return
     */
    @Async
    public void removeBatchByPattern(String pattern) {
        try {
            Set<String> keys = stringRedisTemplate.keys(pattern);
            if (keys != null) {
                stringRedisTemplate.delete(keys);
            }
        } catch (Exception ex) {
            log.error("Redis批量删除Keys失败，原因：{}", ex.getMessage());
        }
    }

    /**
     * 接口 是否触发流控
     *
     * @param apiName
     * @param userId
     * @param standCount
     * @return
     */
    public Boolean airDropCount(String apiName, Integer userId, Long standCount) {

        String key = "AI:FACE:AIRDROPCOUNT:" + apiName + ":USERID:" + userId;

        Long count = stringRedisTemplate.opsForValue().increment(key);
        Long expire = stringRedisTemplate.getExpire(key);

        if (expire == null || expire <= 0) {
            stringRedisTemplate.expire(key, 60, TimeUnit.SECONDS);
        }

        if (count != null && count > standCount) {
            return true;
        } else {
            return false;
        }
    }
}
